//import { fetchMenuData} from '@/api/menu';
 
import request from '../utils/request';
export const fetchMenuData = async () => {
  try {
     const response = await request.post('/sys/menu/query');
    return response.data ; // 假设后端返回的数据格式已经是树形结构
  } catch (error) {
    console.error('Failed to fetch menu data:', error);
    throw error; // 如果需要，可以在这里处理错误
  }
};
// 构建树形结构的函数
export const buildTree = (data: any[]): any[] => {
  const map = new Map<string, any>();
  const tree: any[] = [];

  // 将所有项存储到 map 中
  data.forEach((item) => {
    map.set(item.menuindex, { ...item, children: [] });
  });

  // 构建树形结构
  data.forEach((item) => {
    if (item.parent) {
      const parent = map.get(item.parent);
      if (parent) {
        parent.children.push(map.get(item.menuindex)!);
      }
    } else {
      tree.push(map.get(item.menuindex)!);
    }
  });

  return tree;
};

// 异步获取菜单数据并构建树形结构
export const getMenuTree = async () => {
  const menuData = await fetchMenuData();
  return buildTree(menuData);
};

// 异步获取菜单数据
export const getMenu = async () => {
  const menuData = await fetchMenuData();
  return menuData;
};


// 添加新菜单项
export const addMenuItem = async (menuItem: any) => {
  try {
    
    const response = await request.post('/sys/menu/save', menuItem);
    return response.data ;
  } catch (error) {
    console.error('Failed to add menu item:', error);
    throw error;
  }
};

// 删除菜单项
export const deleteMenuItem = async (Menu: string) => {
  try {
   
    const response = await request.post('/sys/menu/delete', Menu);
    return response;
  } catch (error) {
    console.error('Failed to add menu item:', error);
    throw error;
  }
};
 

// 更新菜单项
export const updateMenuItem = async (Menu: any) => {
  try {
    const response = await request.post('/sys/menu/update', Menu);
    return response.data ;
  } catch (error) {
    console.error('Failed to update menu item:', error);
    throw error;
  }
};

